package com.leetcode.No0008;

/**
 * @program: leetcode
 * @description: 力扣第8道
 * @author: wangzhihua
 * @date: 2021-05-25
 */
public class Solution01 {
	public int myAtoi(String s) {
		// 校验s，去掉多余空格
		if (s == null || (s = s.trim()).length() == 0) {
			return 0;
		}

		// 节省内存，用StringBuilder
		StringBuilder sb = new StringBuilder(s);
		// [start, end)，用了这个后面就不需要截取子串，直接控制前后两个下标即可
		int start = 0, end = sb.length();

		// 处理第一个字符
		boolean isNegativeNumber = false;
		int charAt0 = sb.charAt(0);
		if (charAt0 != '-' && charAt0 != '+' && (charAt0 < '0' || charAt0 > '9')) {
			return 0;
		}
		if (charAt0 == '-') {
			isNegativeNumber = true;
			++start;
		} else if (charAt0 == '+') {
			++start;
		}

		// 遍历字符数组，确定数字start和end的下标范围
		boolean needCheckPrefixZero = true;
		for (int i = start; i < end; ++i) {
			char ch = sb.charAt(i);
			if (needCheckPrefixZero) {
				if (ch == '0') {
					++start;
					continue;
				} else {
					needCheckPrefixZero = false;
				}
			}
			if (ch > '9' || ch < '0') {
				end = i;
				break;
			}
		}
		if (start == end) {
			return 0;
		}

		// 将表示数字的字符串取出，转换为int
		String strResult = isNegativeNumber ? "-" + sb.substring(start, end) : sb.substring(start, end);
		int intResult;
		String maxIntStr = String.valueOf(Integer.MAX_VALUE);
		String minIntStr = String.valueOf(Integer.MIN_VALUE);
		if (!isNegativeNumber &&
				(strResult.length() > maxIntStr.length() ||
						(strResult.length() == maxIntStr.length() && strResult.compareTo(maxIntStr) > 0))) {
			intResult = Integer.MAX_VALUE;

		} else if (isNegativeNumber &&
				(strResult.length() > minIntStr.length() ||
						(strResult.length() == minIntStr.length() && strResult.compareTo(minIntStr) > 0))) {
			intResult = Integer.MIN_VALUE;
		} else {
			intResult = Integer.parseInt(strResult);
		}

		return intResult;
	}

}
